<template>
  <el-popover
    :visible="remarkVisible"
    placement="top-end"
    :width="420"
    trigger="click"
  >
    <template #reference>
      <el-button plain type="success" @click="openRemark">
        <Icon icon="ep:chat-dot-round"/>&nbsp;备注
      </el-button>
    </template>

    <el-form
      label-position="top"
      class="mb-auto"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="添加评论" prop="remark">
        <editor v-model="formData.remark" :height="300"/>
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          :loading="formLoading"
          @click="submitForm"
        >
          提交评论
        </el-button>
        <el-button @click="closeRemark">取消</el-button>
      </el-form-item>
    </el-form>
  </el-popover>
</template>

<script setup lang="ts">
import { ProcessInstanceRemarkApi, ProcessInstanceRemark } from "@/api/bpm/task/remark"

const message = useMessage() // 消息弹窗
const remarkVisible = ref(false)
const formLoading = ref(false)
const formRef = ref() // 表单 Ref
const formData = ref<ProcessInstanceRemark>({
  id: undefined,
  processInstanceId: undefined,
  remark: ''
})

const props = defineProps<{
  processInstance: any // 流程实例信息
  processDefinition: any // 流程定义信息
}>()

const emit = defineEmits(['success']) // 定义 success 事件

const formRules = reactive({
  remark: [{ required: true, message: '评论不能为空', trigger: 'blur' }]
})

/** 打开备注弹窗 */
const openRemark = () => {
  remarkVisible.value = true
  formData.value.processInstanceId = props.processInstance.id
}

/** 关闭备注弹窗 */
const closeRemark = () => {
  remarkVisible.value = false
  resetForm()
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value.validate()

  // 提交请求
  formLoading.value = true
  try {
    await ProcessInstanceRemarkApi.createProcessInstanceRemark(formData.value)
    remarkVisible.value = false
    resetForm()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    processInstanceId: undefined,
    remark: ''
  }
  formRef.value?.resetFields()
}
</script>
